from django.shortcuts import render, redirect
from ManageApp.models import PhoneNumbers
from ManageApp.utils.page_nav import PageNav
from django import forms
from django.core.exceptions import ValidationError
from ManageApp.utils.bootstrap import BootstrapForm


class NumModelForm(BootstrapForm):
    class Meta:
        model = PhoneNumbers
        fields = '__all__'

    # def clean_mobile(self):
    #     #  等价于self.cleaned_data["mobile"] = txt_mobile
    #     # 传回的的数据 赋予clean__##函数后面的##
    #     txt_mobile = self.cleaned_data['mobile']
    #     if len('txt_mobile') != 11:
    #         raise ValidationError("电话格式错误")
    #     if PhoneNumbers.objects.filter(mobile=txt_mobile).exists():
    #         raise ValidationError("电话已存在")
    #     return txt_mobile


class NumModelFormEdit(BootstrapForm):
    mobile = forms.CharField(disabled=True,
                             label="手机号",
                             widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "手机号"}))

    class Meta:
        model = PhoneNumbers
        fields = "__all__"

    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']
        id = self.instance.pk
        if len(txt_mobile) != 11:
            raise ValidationError("格式错误")
        if PhoneNumbers.objects.filter(mobile=txt_mobile).exists():
            raise ValidationError("手机号已存在")
        return txt_mobile


def number_list(req):
    search_data_dict = {}
    search_data = req.GET.get("q", "")
    # GET会从url读取，form表单里get方法也是将参数传给url
    page = int(req.GET.get("page", 1))
    # page是在分页导航中点击页码时自动带上的
    if search_data:  # 如果有要查询的 则输入查询 否则默认全部输出
        search_data_dict["search_data"] = search_data
    queryset = PhoneNumbers.objects.filter(**search_data_dict)

    page_nav_obj = PageNav(req, queryset, page)
    page_queryset = page_nav_obj.page_queryset
    page_nav_string = page_nav_obj.get_html()
    content = {
        "queryset": page_queryset,
        "search_data": search_data,
        "page_nav_string": page_nav_string,
    }
    # return render(req, "num_list.html")
    return render(req, "num_list.html", content)


def number_add(req):
    if req.method == "GET":
        form = NumModelForm()
        content = {
            "form": form,
        }
        return render(req, "num_add.html", content)
    form = NumModelForm(data=req.POST)  # 将前端传给form
    if form.is_valid():
        form.save()
        return redirect("/numbers/list")
    return render(req, "num_add.html", {"form": form})


def number_edit(req, nid):
    obj_row = PhoneNumbers.objects.filter(id=nid)  # 先获取数据
    if req.method == "GET":
        form = NumModelFormEdit(instance=obj_row)  # 因为是编辑，需要把要编辑的数据传给前端
        return render(req, "num_edit.html", {"form": form})
    form = NumModelFormEdit(instance=obj_row, data=req.POST)
    # instance表示要编辑的对象，data表示要编辑的内容
    if form.is_valid():
        form.save()
        return redirect("/numbers/list")
    return render(req, "num_edit.html", {"form": form})


def number_delete(req):
    nid = req.GET.get("nid")
    PhoneNumbers.objects.filter(id=nid).delete()
    return redirect("/numbers/list")
